package com.apes.scm.masterdata.party.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.plugin.mq.annotation.Consumer;
import com.apes.framework.rop.converter.DateUtils;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.res.model.Currency;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.model.Country;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.contrast.model.ContrastPartyCode;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.DeptEnum;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.*;
import com.apes.scm.masterdata.party.repository.*;
import com.apes.scm.masterdata.stock.model.Depot;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.model.StockUsage;
import com.apes.scm.masterdata.stock.repository.DepotRepository;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 功能：公司信息
 *
 * @author Linwz
 * @create 2019-10-24 14:35
 */
@Service("companyEntryService")
public class CompanyEntryService extends DomainService {


    @Autowired
    PartyRepository partyRepository;

    @Autowired
    public PartyService partyService;

    @Autowired
    public PartyRoleService partyRoleService;

    @Autowired
    public PartyIdentificationRepository partyIdentificationRepository;

    @Autowired
    CompanyRepository companyRepository;

    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    CorporateRepository corporateRepository;
    @Autowired
    CorporateSerive corporateSerive;
    @Autowired
    CompanyEntryRepository companyEntryRepository;
    @Autowired
    SequenceService sequenceService;
    @Autowired
    RoleTypeRepository roleTypeRepository;
    @Autowired
    AreaRepository areaRepository;
    @Autowired
    AccessProviderRepository accessProviderRepository;

    @Autowired
    ContrastPartyCodeRepository contrastPartyCodeRepository;

    @Value("${apes.switched:false}")
    private Boolean switched;

    /*
     *  创建公司入驻申请
     * */
    public CompanyEntry save(SimpleRequest request) {
        // 获取模型
        CompanyEntry companyEntry = request.getO(CompanyEntry.class);
        checkOperator(companyEntry);
//        checkCompanyEntry(companyEntry);
        companyEntry.setState("create");
        return companyEntryRepository.saveAndFlush(companyEntry);

    }

    // 更新公司信息
    public CompanyEntry update(SimpleRequest request) {
        // 获取模型
        CompanyEntry companyEntry = request.getO(CompanyEntry.class);
        checkOperator(companyEntry);
        return companyEntryRepository.saveAndFlush(companyEntry);
    }

    private void checkOperator(CompanyEntry companyEntry){
        if (companyEntry.isOperatorSign() && companyEntry.getBelongOperator() != null) throw new RuntimeException("运营商不能有所属运营商!");
    }

//    /**
//     * 保存时判断填入的编码是否与已有公司重复，是否与已有待审核的“公司入驻申请”重复
//     *
//     * @param companyEntry
//     */
//    public void checkCompanyEntry(CompanyEntry companyEntry) {
//        Party party = partyRepository.findByOrigin(String.valueOf(companyEntry.getCode()));
////        PartyRole partyRole = partyRoleRepository.findByPartyIdAndRoleId(party.getId(),"Company");
//        if (party != null) throw new RuntimeException("该公司已经存在，不予许重复生成。");
//        CompanyEntry entry = companyEntryRepository.findByCode(companyEntry.getCode());
//        if (entry != null) throw new RuntimeException("已有待审核的公司入驻申请!");
//    }

    /**
     * 根据SUCC角色信息
     *
     * @param request
     * @return
     */
    public CompanyEntry findCompanyEntryBySUCC(SimpleRequest request) {
        String code = request.get("uscc");
        CompanyEntry companyEntry = companyEntryRepository.findByUscc(code);
        return companyEntry;
    }

    /**
     * 通过审批 生成 party 和 公司，供应商 ，单位客户
     * 三个角色的 partyRole
     * 以及同步到旧系统
     *
     * @param request
     * @return
     */
    public CompanyEntry savePartyAndRole(SimpleRequest request) {
        CompanyEntry companyEntry = request.getO(CompanyEntry.class);
        if (partyRepository.findAll(JpaDsl.toCriteriaByEq("name", companyEntry.getName())).size() > 0) {
            throw new RuntimeException(String.format("公司[%s]存在同名的公司或供应商！请检查数据！", companyEntry.getName()));
        }
        JSONObject body = new JSONObject();
        // 获取注册区县
        Area regCounty = companyEntry.getRegCounty();// 注册地址.区县
        // 获取注册城市编码
        String regCityId = regCounty.getParent();
        // 查找注册城市
        Area regCity = areaRepository.findOne(regCityId);
        companyEntry.setRegCity(regCity); // 注册地址.城市
        // 设置注册城市
        String regProvinceId = regCity.getParent();
        Area regProvince = areaRepository.findOne(regProvinceId);
        companyEntry.setRegProvince(regProvince); //注册地址.省份
        // 获取注册区县
        Area officeCounty = companyEntry.getOfficeCounty();// 办公地点.区县
        String officeCityId = officeCounty.getParent();
        Area officeCity = areaRepository.findOne(officeCityId);
        companyEntry.setOfficeCity(officeCity);// 办公地点.城市
        String officeProvinceId = officeCity.getParent();
        Area officeProvince = areaRepository.findOne(officeProvinceId);
        companyEntry.setOfficeProvince(officeProvince);// 办公地点.省份
        companyEntry = companyEntryRepository.saveAndFlush(companyEntry);
        //写入part
        Party party = companyEntryToParty(companyEntry, body);
        // 接入商及公司
        PartyRole partyRole = partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company");
        AccessProvider accessProvider = accessProviderRepository.findOne(companyEntry.getAccessProvider().getId());
        List<PartyRole> partyRoleList = accessProvider.getCompanys();
        partyRoleList.add(partyRole);
        accessProvider.setCompanys(partyRoleList);
        SpringManager.getBean(AccessProviderService.class).checkSettlementCenter(accessProvider);
        accessProviderRepository.saveAndFlush(accessProvider);

        companyEntry.setParty(party);
        companyEntry.setState("approve");
        companyEntry.setCode(partyRole.getId());
        synLocalPermit(partyRole, body);
        writeContrastPartyCode(party);
        synDept(partyRole);
        MQUtil.publish("cm.companyEntry.synUnifiedExport", "公司入驻", body);
        return companyEntry;
    }

    /**
     * 将 公司入驻申请 的 数据 填入 party
     *
     * @param companyEntry
     * @return
     */
    public Party companyEntryToParty(CompanyEntry companyEntry, JSONObject body) {
//        long id = companyEntry.getId();
//        long id = companyEntry.getCode();
        String name = companyEntry.getName();// 当事人名称
        String abbreviation = companyEntry.getAbbreviation();// 简称
        String bank = companyEntry.getBank();// 开户行
        String bankAccount = companyEntry.getBankAccount();// 银行帐号
        String invoiceTitle = companyEntry.getInvoiceTitle();// 发票抬头
        String invoiceAddress = companyEntry.getInvoiceAddress();// 发票地址
        String invoicePhone = companyEntry.getInvoicePhone();// 发票电话
        String origin = companyEntry.getOrigin();// 外部ID
        Enumeration companyNature = companyEntry.getCompanyNature();// 公司性质编码
        // 获取注册区县
        Area regCounty = companyEntry.getRegCounty();// 注册地址.区县
        // 查找注册城市
        Area regCity = companyEntry.getRegCity();
        // 设置注册城市
        Area regProvince = companyEntry.getRegProvince();
        // 获取注册区县
        Area officeCounty = companyEntry.getOfficeCounty();// 办公地点.区县
        Area officeCity = companyEntry.getOfficeCity();
        Area officeProvince = companyEntry.getOfficeProvince();

        Country regCountry = companyEntry.getRegCountry();// 注册地址.国家
        String regAddress = companyEntry.getRegAddress();// 注册地址.地址
        Country officeCountry = companyEntry.getOfficeCountry();// 办公地点.国家
        String officeAddress = companyEntry.getOfficeAddress();// 办公地点.地址
        String postalCode = companyEntry.getPostalCode();// 邮政编码
        String uscc = companyEntry.getUscc();// 统一社会信用代码
        double registeredCapital = companyEntry.getRegisteredCapital();// 注册资金【万元】
        Enumeration operation = companyEntry.getOperation();// 运营模式
        Enumeration purchaseInvoice = companyEntry.getPurchaseInvoice();// 默认采购发票设置
        Currency currency = companyEntry.getCurrency();// 币种
        Double maxInvoiceValue = companyEntry.getMaxInvoiceValue();//最大发票金额
//        Tax tax = companyEntry.getTax();// 销项税率
        Enumeration taxpayer = companyEntry.getTaxpayer();//纳税人

        Enumeration supplierLevel = companyEntry.getSupplierLevel();// 供应商级别

        Enumeration customerGroup = companyEntry.getCustomerGroup();// 客户组
        Enumeration customerCategory = companyEntry.getCustomerCategory();// 客户类别
        Enumeration shipmentConditions = companyEntry.getShipmentConditions();// 装运条件
        String deliveryPlace = companyEntry.getDeliveryPlace();// 交货地点
        Enumeration customerCreditGroup = companyEntry.getCustomerCreditGroup();// 客户信用组编码
        boolean isWantInvoice = companyEntry.isWantInvoice();// 是否要发票
        boolean isCanInvoice = companyEntry.isCanInvoice();// 能否发票
        boolean valid = companyEntry.isValid();// 有效

        Party party = new Party();
        party.setName(name);
        party.setAbbreviation(abbreviation);
        party.setBank(bank);
        party.setBankAccount(bankAccount);
        party.setInvoiceTitle(invoiceTitle);
        party.setInvoiceAddress(invoiceAddress);
        party.setInvoicePhone(invoicePhone);
//        party.setOrigin(sequenceServiceId);
        Corporate corporate = new Corporate();
        corporate.setCompanyNature(companyNature);
        corporate.setRegCountry(regCountry);
        corporate.setRegProvince(regProvince);
        corporate.setRegCity(regCity);
        corporate.setRegCounty(regCounty);
        corporate.setRegAddress(regAddress);
        corporate.setOfficeCountry(officeCountry);
        corporate.setOfficeProvince(officeProvince);
        corporate.setOfficeCity(officeCity);
        corporate.setOfficeCounty(officeCounty);
        corporate.setOfficeAddress(officeAddress);
        corporate.setPostalCode(postalCode);
        corporate.setUscc(uscc);
        corporate.setRegisteredCapital(registeredCapital);
        corporate.setCurrency(currency);
        corporate.setMaxInvoiceValue(maxInvoiceValue);
//        corporate.setTax(tax);
        corporate.setTaxpayer(taxpayer);
        corporate.setSupplierLevel(supplierLevel);
        corporate.setCustomerGroup(customerGroup);
        corporate.setCustomerCategory(customerCategory);
        corporate.setShipmentConditions(shipmentConditions);
        corporate.setDeliveryPlace(deliveryPlace);
        corporate.setCustomerCreditGroup(customerCreditGroup);
        corporate.setWantInvoice(isWantInvoice);
        corporate.setCanInvoice(isCanInvoice);
        corporate.setValid(valid);
        corporate.setOperation(operation);
        corporate.setPurchaseInvoice(purchaseInvoice);
        corporate.setMobileNumber(companyEntry.getPhoneNumber());
        corporate.setIcon(companyEntry.getLogo());
        party.setCorporate(corporate);

        // 设置当事人类型
        party.setPartyType("corporate");
        party.setSettlementCenter(companyEntry.isSettlementCenter());
        // 设置当事人运营商相关类型
        party.setOperatorSign(companyEntry.isOperatorSign());
        party.setBelongOperator(companyEntry.getBelongOperator());
        savePartyRole(party);
        partyService.operatorProcess(party);
        party = partyRepository.saveAndFlush(party);
        synCompanyAndSupplierAndCustomer(party, companyEntry, body);
        return party;


    }

    /**
     * 保存公司
     *
     * @param party
     * @return
     */
    private void savePartyRole(Party party) {
        PartySerialNumber serialNumber = new PartySerialNumber();
        serialNumber = serialNumber.checkParty(party);
        String sequenceServiceId = String.format("%4d", serialNumber.getCompanyId()).replace(" ", "0");
        //唯一标识 角色
        Set<PartyIdentification> partyIdentifications = new HashSet<>();
        Set<PartyRole> partyRoles = new HashSet<>();

        // 创建角色类型为  Company
        // 获取角色对应编码
        PartyRole companyPartyRole = new PartyRole();
        companyPartyRole.setId(sequenceServiceId);
        companyPartyRole.setParty(party);
        companyPartyRole.setRole(roleTypeRepository.findOne("Company"));
        partyRoles.add(companyPartyRole);

//        PartyIdentification usccPartyIdentification = new PartyIdentification();
//        usccPartyIdentification.setParty(party);
//        usccPartyIdentification.setPartyIdType("PIT_USCC");
//        usccPartyIdentification.setIdValue(party.getCorporate().getUscc());
//        partyIdentifications.add(usccPartyIdentification);

        // 创建角色类型为  Customer
        PartyRole customerPartyRole = new PartyRole();
        customerPartyRole.setId("K" + sequenceServiceId);
        customerPartyRole.setParty(party);
        customerPartyRole.setRole(roleTypeRepository.findOne("Customer"));
        partyRoles.add(customerPartyRole);

        PartyIdentification CpartyIdentification = new PartyIdentification();
        CpartyIdentification.setParty(party);
        CpartyIdentification.setPartyIdType("CustomerCode");
        CpartyIdentification.setIdValue("K" + sequenceServiceId);
        partyIdentifications.add(CpartyIdentification);

        // 创建角色类型为  Supplier
        // 获取角色对应编码
        PartyRole SpartyRole = new PartyRole();
        SpartyRole.setId("G" + sequenceServiceId);
        SpartyRole.setParty(party);
        SpartyRole.setRole(roleTypeRepository.findOne("Supplier"));
        partyRoles.add(SpartyRole);
        PartyIdentification SpartyIdentification = new PartyIdentification();
        SpartyIdentification.setParty(party);
        SpartyIdentification.setPartyIdType("SupplierCode");
        SpartyIdentification.setIdValue("G" + sequenceServiceId);
        partyIdentifications.add(SpartyIdentification);

        PartyIdentification companyPartyIdentification = new PartyIdentification();
        companyPartyIdentification.setParty(party);
        companyPartyIdentification.setPartyIdType("CompanyCode");
        companyPartyIdentification.setIdValue(sequenceServiceId);
        partyIdentifications.add(companyPartyIdentification);

        party.setOrigin(sequenceServiceId);
        party.setPartyIdentifications(partyIdentifications);
        party.setPartyRoles(partyRoles);
    }

    public void synCompanyAndSupplierAndCustomer(Party party, CompanyEntry entry, JSONObject body) {
//        Party newParty = request.getO(Party.class);
//        Party party = partyRepository.findOne(newParty.getId());
        Corporate corporate = corporateRepository.findOne(party.getCorporate().getId());
        party.getPartyRoles().stream().forEach(partyRole -> {
            if (partyRole.getRole().getId().equals("Company")) {
                JSONObject synCompany = new JSONObject();
                synCompany.put("GSID", partyRole.getId());
                synCompany.put("GSMC", party.getName());
                synCompany.put("GSJC", party.getAbbreviation());
                synCompany.put("GJID", corporate.getRegCountry().getId());
                synCompany.put("GJMC", corporate.getRegCountry().getName());
                synCompany.put("SFID", corporate.getRegProvince().getId().substring(0, corporate.getRegProvince().getId().length() - 4));
                synCompany.put("SFMC", corporate.getRegProvince().getName());
                synCompany.put("CSID", corporate.getRegCity().getId().substring(0, corporate.getRegCity().getId().length() - 2));
                synCompany.put("CSMC", corporate.getRegCity().getName());
                synCompany.put("ZCDZ", corporate.getRegAddress());
                synCompany.put("GSKHYH", party.getBank());
                synCompany.put("GSZH", party.getBankAccount());
                synCompany.put("GSSH", corporate.getUscc());
                synCompany.put("LXR", entry.getContacts()==null?"无":entry.getContacts());
                synCompany.put("LXDH", entry.getContactsNumber()==null?"无":entry.getContactsNumber());
                synCompany.put("SJHM", entry.getPhoneNumber()==null?"无":entry.getPhoneNumber());
                synCompany.put("YXBJ", corporate.isValid() ? 1 : 0);
//                synCompany.put("BZ",);
                synCompany.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synCompany.put("LRR", "admin");
                synCompany.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synCompany.put("YZBM", corporate.getPostalCode()==null?"无":corporate.getPostalCode());
//                synCompany.put("PYM",);
                synCompany.put("KHID", "K" + partyRole.getId());
                synCompany.put("GYSID", "G" + partyRole.getId());
                String description = corporate.getOperation().getDescription();
                int YYMS = 0;
                if (description.equals("合伙人")) {
                    YYMS = 1;
                }
                if (description.equals("赋能店")) {
                    YYMS = 2;
                }
                synCompany.put("YYMS", YYMS);
//                String topic = "event:cm.companyEntry.synCompany";
//                Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synCompany).stream().findFirst().get();
//                if (!flg) {
//                    throw new RuntimeException("公司同步到旧框架时报错!");
//                }
                body.put("Company", synCompany);
                if (entry.isUse()) {
                    //同步旧系统 STR_FNKCTBFW
//                    String FNKCTBFWTopic = "event:cm.companyEntry.synFNKCTBFW";
//                    Boolean FNKCTBFWTlg = (Boolean) EventUtil.sendSynEvent(this, FNKCTBFWTopic, MapUtil.mapper("GSID", partyRole.getId())).stream().findFirst().get();
//                    if (!FNKCTBFWTlg) {
//                        throw new RuntimeException("赋能同步到旧框架时报错!");
//                    }
                    body.put("FNKCTBFW", MapUtil.mapper("GSID", partyRole.getId()));
                }
                // 生成公司后要生成 采购组织
                JSONObject synCGZZ = new JSONObject();
                synCGZZ.put("CGZZID", partyRole.getId());
                synCGZZ.put("CGZZMC", party.getName());
                synCGZZ.put("GSID", partyRole.getId());
                synCGZZ.put("YXBJ", corporate.isValid() ? 1 : 0);
                synCGZZ.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synCGZZ.put("LRR", "admin");
                synCGZZ.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synCGZZ.put("GSMC", party.getName());
//                String CGZZTopic = "event:cm.companyEntry.synCGZZ";
//                Boolean CGZZFlg = (Boolean) EventUtil.sendSynEvent(this, CGZZTopic, synCGZZ).stream().findFirst().get();
//                if (!CGZZFlg) {
//                    throw new RuntimeException("采购组织同步到旧框架时报错!");
//                }
                body.put("CGZZ", synCGZZ);

                // 生成公司后要生成 销售组织
                JSONObject synXSZZ = new JSONObject();
                synXSZZ.put("XSZZID", partyRole.getId());
                synXSZZ.put("XSZZMC", party.getName());
                synXSZZ.put("GSID", partyRole.getId());
                synXSZZ.put("YXBJ", corporate.isValid() ? 1 : 0);
                synXSZZ.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synXSZZ.put("LRR", "admin");
                synXSZZ.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synXSZZ.put("GSMC", party.getName());
//                String XSZZTopic = "event:cm.companyEntry.synXSZZ";
//                Boolean XSZZFlg = (Boolean) EventUtil.sendSynEvent(this, XSZZTopic, synXSZZ).stream().findFirst().get();
//                if (!XSZZFlg) {
//                    throw new RuntimeException("销售组织同步到旧框架时报错!");
//                }
                body.put("XSZZ", synXSZZ);

                // 生成公司后要生成 与1001与当前公司的价格权益
                PartyRole partyRole1001 = partyRoleRepository.findById("1001").get();
                JSONObject synQYFW = new JSONObject();
                synQYFW.put("SSGSID", partyRole1001.getId());
                synQYFW.put("SSGSMC", partyRole1001.getName());
                synQYFW.put("JYGSID", partyRole.getId());
                synQYFW.put("JYGSMC",party.getName());
                synQYFW.put("QYLX", 6);
                synQYFW.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synQYFW.put("LRR", "admin");
                synQYFW.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));

                body.put("QYFW", synQYFW);
            }

            if (partyRole.getRole().getId().equals("Supplier")) {

                JSONObject synSupplier = new JSONObject();
                synSupplier.put("GYSID", "G" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synSupplier.put("GYSMC", party.getName());

                synSupplier.put("GYSJC", party.getAbbreviation());
                synSupplier.put("GJID", corporate.getRegCountry().getId());
                synSupplier.put("SFID", corporate.getRegProvince().getId().substring(0, corporate.getRegProvince().getId().length() - 4));
                synSupplier.put("CSID", corporate.getRegCity().getId().substring(0, corporate.getRegCity().getId().length() - 2));
                synSupplier.put("QXID", corporate.getRegCounty().getId());
//                synSupplier.put("PYM",);
                synSupplier.put("DZ", corporate.getRegAddress());
//                synSupplier.put("BZ",);

                synSupplier.put("GSID", partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synSupplier.put("KHID", "K" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Customer").getId());
                synSupplier.put("SPGYSBJ", 1);
                synSupplier.put("WLGYSBJ", 0);
                synSupplier.put("FWGYSBJ", 0);
                synSupplier.put("CCGYSBJ", 0);
                synSupplier.put("ZFGYSBJ", 0);
                synSupplier.put("YXBJ", 1);
                synSupplier.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synSupplier.put("LRR", "admin");

                synSupplier.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synSupplier.put("BXGYSBJ", 0);
                //性质编码对不上
                String description = corporate.getCompanyNature().getDescription();
                synSupplier.put("GSXZMC", corporate.getCompanyNature().getDescription());
                if (description.equals("有限责任公司")) {
                    synSupplier.put("GSXZID", 1);
                }
                if (description.equals("股份有限公司")) {
                    synSupplier.put("GSXZID", 2);
                }
                if (description.equals("合伙企业")) {
                    synSupplier.put("GSXZID", 8);
                }
                if (description.equals("国有企业")) {
                    synSupplier.put("GSXZID", 4);
                }
                if (description.equals("个体户")) {
                    synSupplier.put("GSXZID", 9);
                }
                if (corporate.getSupplierLevel()!=null){
                    String supplierLevel = corporate.getSupplierLevel().getDescription();

                    if (supplierLevel.equals("A级")) {
                        synSupplier.put("DWJB", 0);
                    }
                    if (supplierLevel.equals("B级")) {
                        synSupplier.put("DWJB", 1);
                    }
                    if (supplierLevel.equals("C级")) {
                        synSupplier.put("DWJB", 2);
                    }
                    if (supplierLevel.equals("D级")) {
                        synSupplier.put("DWJB", 3);
                    }
                    if (supplierLevel.equals("E级")) {
                        synSupplier.put("DWJB", 4);
                    }
                }


                synSupplier.put("JJGYSBJ", 0);
                synSupplier.put("SHGYSBJ", 0);
                synSupplier.put("NBGYSBJ", 1);
//                String topic = "event:cm.companyEntry.synSupplier";
//                Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synSupplier).stream().findFirst().get();
//                if (!flg) {
//                    throw new RuntimeException("供应商同步到旧框架时报错!");
//                }
                body.put("Supplier", synSupplier);

                // 生成供应商后要生成 采购组织分配供应商
                JSONObject synCGZZGYS = new JSONObject();
                synCGZZGYS.put("CGZZID", partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synCGZZGYS.put("CGZZMC", partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getName());
                synCGZZGYS.put("GYSID", "G" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synCGZZGYS.put("GYSMC", party.getName());
                synCGZZGYS.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synCGZZGYS.put("LRR", "admin");
                synCGZZGYS.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
//                String CGZZGYSTopic = "event:cm.companyEntry.synCGZZGYS";
//                Boolean CGZZGYSFlg = (Boolean) EventUtil.sendSynEvent(this, CGZZGYSTopic, synCGZZGYS).stream().findFirst().get();
//                if (!CGZZGYSFlg) {
//                    throw new RuntimeException("采购组织分配供应商同步到旧框架时报错!");
//                }
                body.put("CGZZGYS", synCGZZGYS);
                // 生成供应商后要生成 供应商注册信息
                JSONObject synGYSZCXX = new JSONObject();
                synGYSZCXX.put("GYSID", "G" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synGYSZCXX.put("GYSMC", party.getName());
                synGYSZCXX.put("GJID", corporate.getRegCountry().getId());
                synGYSZCXX.put("SFID", corporate.getRegProvince().getId().substring(0, corporate.getRegProvince().getId().length() - 4));
                synGYSZCXX.put("CSID", corporate.getRegCity().getId().substring(0, corporate.getRegCity().getId().length() - 2));
                synGYSZCXX.put("QXID", corporate.getRegCounty().getId());
                synGYSZCXX.put("DZ", corporate.getRegAddress());

                synGYSZCXX.put("KHYH", party.getBank());
                synGYSZCXX.put("ZH", party.getBankAccount());
                synGYSZCXX.put("SH", corporate.getUscc());
                synGYSZCXX.put("ZZJGDM", corporate.getUscc());
                synGYSZCXX.put("FRDB", entry.getRepresentative());
                synGYSZCXX.put("YZBM",  corporate.getPostalCode()==null?"无":corporate.getPostalCode());
                synGYSZCXX.put("ZCZJ_2", corporate.getRegisteredCapital());
                synGYSZCXX.put("ZCHBDW", 0);
                synGYSZCXX.put("ZCZJ", corporate.getRegisteredCapital());
//                String GYSZCXXTopic = "event:cm.companyEntry.synGYSZCXX";
//                Boolean GYSZCXXFlg = (Boolean) EventUtil.sendSynEvent(this, GYSZCXXTopic, synGYSZCXX).stream().findFirst().get();
//                if (!GYSZCXXFlg) {
//                    throw new RuntimeException("供应商注册信息同步到旧框架时报错!");
//                }
                body.put("GYSZCXX", synGYSZCXX);
                // 生成供应商后要生成 供应商财务信息
                JSONObject synGYSCWXX = new JSONObject();
                synGYSCWXX.put("GYSID", "G" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synGYSCWXX.put("GYSMC", party.getName());
                //synGYSCWXX.put("SSLBID", party.getCorporate().getTax().getOrigin());
                //synGYSCWXX.put("SSBL", party.getCorporate().getTax().getAmt()/100);
                synGYSCWXX.put("KPBJ", corporate.isCanInvoice() ? 1 : 0);
                synGYSCWXX.put("FPTT", party.getInvoiceTitle());
                synGYSCWXX.put("FPDZ", party.getInvoiceAddress());
                synGYSCWXX.put("FPDH", party.getInvoicePhone());
//                String name = corporate.getTax().getName();
//                if (name.equals("16%增值税")) {
//                    synGYSCWXX.put("SSLBID", "J9");
//                }
//                if (name.equals("10%增值税")) {
//                    synGYSCWXX.put("SSLBID", "J8");
//                }
//                if (name.equals("13%增值税")) {
//                    synGYSCWXX.put("SSLBID", "J5");
//                }
//                if (name.equals("6%增值税")) {
//                    synGYSCWXX.put("SSLBID", "J4");
//                }
//                if (name.equals("5%增值税")) {
//                    synGYSCWXX.put("SSLBID", "J3");
//                }
//                if (name.equals("3%增值税")) {
//                    synGYSCWXX.put("SSLBID", "J2");
//                }
//                if (name.equals("1.5%增值税")) {
//                    synGYSCWXX.put("SSLBID", "J1");
//                }
//                if (name.equals("无税")) {
//                    synGYSCWXX.put("SSLBID", "J0");
//                }

                synGYSCWXX.put("QPFS", 0);
                synGYSCWXX.put("ZGKPJE", corporate.getMaxInvoiceValue());

//                String GYSCWXXTopic = "event:cm.companyEntry.synGYSCWXX";
//                Boolean GYSCWXXFlg = (Boolean) EventUtil.sendSynEvent(this, GYSCWXXTopic, synGYSCWXX).stream().findFirst().get();
//                if (!GYSCWXXFlg) {
//                    throw new RuntimeException("供应商注册信息同步到旧框架时报错!");
//                }
                body.put("GYSCWXX", synGYSCWXX);

            }
            if (partyRole.getRole().getId().equals("Customer")) {
                JSONObject synCustomer = new JSONObject();
                synCustomer.put("KHID", "K" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synCustomer.put("KHMC", party.getName());

                synCustomer.put("KHJC", party.getAbbreviation());
//                synCustomer.put("KHZID",corporate.getCustomerGroup().getId());
                corporate.getCustomerCreditGroup();
                corporate.isWantInvoice();
//                synCustomer.put("KHLBID",corporate.getCustomerCategory());
//                synCustomer.put("PYM",);
                synCustomer.put("DWBJ", 1);

                synCustomer.put("DYGSID", partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synCustomer.put("DYGYSID", "G" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
//                synCustomer.put("DYDDID",);
                synCustomer.put("JHYXQ", 1);

//                synCustomer.put("ZYTJ",corporate.getShipmentConditions());
                synCustomer.put("JHDD", corporate.getDeliveryPlace());
                synCustomer.put("BFJHBJ", 0);
                synCustomer.put("JHBZXE", 0);
                synCustomer.put("JHGLXE", 0);
                synCustomer.put("YXBJ", 1);
//                synCustomer.put("BZ",);
                synCustomer.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synCustomer.put("LRR", "admin");

                synCustomer.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                String description = corporate.getCompanyNature().getDescription();
                if (description.equals("有限责任公司")) {
                    synCustomer.put("GSXZID", 1);
                }
                if (description.equals("股份有限公司")) {
                    synCustomer.put("GSXZID", 2);
                }
                if (description.equals("合伙企业")) {
                    synCustomer.put("GSXZID", 8);
                }
                if (description.equals("国有企业")) {
                    synCustomer.put("GSXZID", 4);
                }
                if (description.equals("个体户")) {
                    synCustomer.put("GSXZID", 9);
                }
                synCustomer.put("GSXZMC", corporate.getCompanyNature().getDescription());
                synCustomer.put("DYGSMC", party.getName());
                synCustomer.put("DYGYSMC", party.getName());
//                synCustomer.put("DYDDMC",party.getName());
                synCustomer.put("DH", entry.getContactsNumber());
//                synCustomer.put("CZHM",);
                synCustomer.put("SJ", entry.getPhoneNumber());
//                synCustomer.put("GSXZ",);
//                synCustomer.put("PSFS",);
                synCustomer.put("LXRXM", entry.getContacts());
//                synCustomer.put("LXRZW",);

                synCustomer.put("DFDWBJ", 0);
                synCustomer.put("JTNBJ", 0);

//                synCustomer.put("BMID",);
//                synCustomer.put("BMMC",);
//
//                String topic = "event:cm.companyEntry.synCustomer";
//                Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synCustomer).stream().findFirst().get();
//                if (!flg) {
//                    throw new RuntimeException("单位客户同步到旧框架时报错!");
//                }
                body.put("Customer", synCustomer);

                JSONObject synKHCWXX = new JSONObject();
                synKHCWXX.put("KHID", "K" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synKHCWXX.put("KHMC", party.getName());

                synKHCWXX.put("KHXYZID", "001");//旧框架只有一个
                // 税收类别编码
//                String name = corporate.getTax().getName();
//                if (name.equals("16%增值税")) {
//                    synKHCWXX.put("SSLBID", "J9");
//                }
//                if (name.equals("10%增值税")) {
//                    synKHCWXX.put("SSLBID", "J8");
//                }
//                if (name.equals("13%增值税")) {
//                    synKHCWXX.put("SSLBID", "J5");
//                }
//                if (name.equals("6%增值税")) {
//                    synKHCWXX.put("SSLBID", "J4");
//                }
//                if (name.equals("5%增值税")) {
//                    synKHCWXX.put("SSLBID", "J3");
//                }
//                if (name.equals("3%增值税")) {
//                    synKHCWXX.put("SSLBID", "J2");
//                }
//                if (name.equals("1.5%增值税")) {
//                    synKHCWXX.put("SSLBID", "J1");
//                }
//                if (name.equals("无税")) {
//                    synKHCWXX.put("SSLBID", "J0");
//                }

                synKHCWXX.put("KPBJ",  corporate.isCanInvoice() ? 1 : 0);
                synKHCWXX.put("FPTT", party.getInvoiceTitle());
                synKHCWXX.put("FPDZ", party.getInvoiceAddress());
                synKHCWXX.put("FPDH", party.getInvoicePhone());
                synKHCWXX.put("YZBM",  corporate.getPostalCode()==null?"无":corporate.getPostalCode());
//                String KHCWXXTopic = "event:cm.companyEntry.synKHCWXX";
//                Boolean KHCWXXFlg = (Boolean) EventUtil.sendSynEvent(this, KHCWXXTopic, synKHCWXX).stream().findFirst().get();
//                if (!KHCWXXFlg) {
//                    throw new RuntimeException("客户财务信息同步到旧框架时报错!");
//                }
                body.put("KHCWXX", synKHCWXX);
                JSONObject synKHZCXX = new JSONObject();
                synKHZCXX.put("KHID", "K" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synKHZCXX.put("KHMC", party.getName());
                synKHZCXX.put("GJID", corporate.getRegCountry().getId());
                synKHZCXX.put("SFID", corporate.getRegProvince().getId().substring(0, corporate.getRegProvince().getId().length() - 4));
                synKHZCXX.put("CSID", corporate.getRegCity().getId().substring(0, corporate.getRegCity().getId().length() - 2));
                synKHZCXX.put("QXID", corporate.getRegCounty().getId());
                synKHZCXX.put("DZ", corporate.getRegAddress());
                synKHZCXX.put("KHYH", party.getBank());
                synKHZCXX.put("ZH", party.getBankAccount());
                synKHZCXX.put("SH", corporate.getUscc());

                synKHZCXX.put("ZZJGDM", corporate.getUscc());
                synKHZCXX.put("FRDB", entry.getRepresentative());
                synKHZCXX.put("SJHM", entry.getPhoneNumber()==null?"无":entry.getPhoneNumber());
                synKHZCXX.put("LXDH", entry.getContactsNumber()==null?"无":entry.getContactsNumber());
                synKHZCXX.put("YZBM", corporate.getPostalCode()==null?"无":corporate.getPostalCode());
//
//                String KHZCXXTopic = "event:cm.companyEntry.synKHZCXX";
//                Boolean KHZCXXFlg = (Boolean) EventUtil.sendSynEvent(this, KHZCXXTopic, synKHZCXX).stream().findFirst().get();
//                if (!KHZCXXFlg) {
//                    throw new RuntimeException("客户注册信息同步到旧框架时报错!");
//                }
                body.put("KHZCXX", synKHZCXX);

//                内部交易对照表
                JSONObject synNBJYDZB = new JSONObject();
                synNBJYDZB.put("SYGSID", "1001");
                synNBJYDZB.put("SYGSMC", "广州市集群车宝汽车服务连锁有限公司");
                synNBJYDZB.put("XSZZID", "1001");
                synNBJYDZB.put("XSZZMC", "广州市集群车宝汽车服务连锁有限公司");
                synNBJYDZB.put("GYSID", "G1001");
                synNBJYDZB.put("GYSMC", "广州市集群车宝汽车服务连锁有限公司");
                synNBJYDZB.put("XYGSID", partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synNBJYDZB.put("XYGSMC", party.getName());
                synNBJYDZB.put("CGZZID", partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synNBJYDZB.put("CGZZMC", party.getName());

                synNBJYDZB.put("KHID", "K" + partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId());
                synNBJYDZB.put("KHMC", entry.getName());
                synNBJYDZB.put("QDID", "40");
                synNBJYDZB.put("QDMC", "调拨");
                synNBJYDZB.put("HZFS", "1");
                synNBJYDZB.put("TS01", DateUtils.format(party.getLastUpdatedStamp(), "yyyyMMdd.HHmmss.SSS"));
                synNBJYDZB.put("LRR", "yyadmin");
                synNBJYDZB.put("LRRQ_SJ", DateUtil.format(party.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                synNBJYDZB.put("MDID", "BY02");
                synNBJYDZB.put("MDMC", "广州车宝内销部");
                synNBJYDZB.put("RYID", "0000252");
                synNBJYDZB.put("RYMC", "冯燕丹");
                synNBJYDZB.put("SYCGZZID", "1001");
                synNBJYDZB.put("SYCGZZMC", "广州市集群车宝汽车服务连锁有限公司");
                synNBJYDZB.put("NXBJ", 0);
//                String NBJYDZBTopic = "event:cm.companyEntry.synNBJYDZB";
//                Boolean NBJYDZBFlg = (Boolean) EventUtil.sendSynEvent(this, NBJYDZBTopic, synNBJYDZB).stream().findFirst().get();
//                if (!NBJYDZBFlg) {
//                    throw new RuntimeException("内部交易对照表同步到旧框架时报错!");
//                }
                body.put("NBJYDZB", synNBJYDZB);

            }
        });

    }

    /**
     * 生成业务部门
     *
     * @param company
     */
    public void synDept(PartyRole company) {
        Dept dept = new Dept();
        dept.setCompany(company);
        dept.setName(company.getName());
        dept.setValid(true);
        dept.setInnerTag(true);
        dept.addDeptType(DeptEnum.RETAIL);
        dept.addDeptType(DeptEnum.PURCHASE);
        dept.addDeptType(DeptEnum.SALE);
        dept.setId(dept.obtainDeptId(dept));
        Dept result = SpringManager.getBean(DeptRepository.class).saveAndFlush(dept);
        if(!switched) {
            synContract(company, result);
        }
        synDepotAndLocation(company, result);
    }

    /**
     * 生成采购合同
     *
     * @param company
     * @param dept
     */
    public void synContract(PartyRole company, Dept dept) {
        String contractApprove = "event:companyEntry.contract.approve";
        Date date = DateUtil.ULocalDateToDate(DateUtil.UDateToLocalDate(new Date()).plusYears(10));
        EventUtil.sendSynEvent(this, contractApprove, invoke("scm.contract.saveNew", MapUtil.mapper("name", company.getId() + "集群车宝经销合同", "cooperation", MapUtil.mapper("id", "distribution"), "contractType", MapUtil.mapper("id", "Contract.contractType.supplier"),
                "company", MapUtil.mapper("id", company.getId()), "partner", MapUtil.mapper("id", "A1001"), "dept", MapUtil.mapper("id", dept.getId()), "validFrom", new Date().getTime(), "validPeriod", date.getTime(),
                "settlementType", MapUtil.mapper("id", "001421")
        )));
        EventUtil.sendSynEvent(this, contractApprove, invoke("scm.contract.saveNew", MapUtil.mapper("name", company.getId() + "集群车宝代销合同", "cooperation", MapUtil.mapper("id", "consignment"), "contractType", MapUtil.mapper("id", "Contract.contractType.supplier"),
                "company", MapUtil.mapper("id", company.getId()), "partner", MapUtil.mapper("id", "A1001"), "dept", MapUtil.mapper("id", dept.getId()), "validFrom", new Date().getTime(), "validPeriod", date.getTime(),
                "settlementType", MapUtil.mapper("id", "001421"))
        ));

    }

    /**
     * 生成逻辑仓库及仓库库区 （不同步至老系统，后期如有需要在修改）
     *
     * @param company
     * @param dept
     */
    public void synDepotAndLocation(PartyRole company, Dept dept) {
        //生成逻辑仓库
        Depot depot = new Depot();
        depot.setName(dept.getName() + "虚拟仓");
        depot.setCompany(company);
        depot.setDisplayName(dept.getName() + "虚拟仓");
        depot.setValid(true);
        depot.setId(depot.obtainDepotId(depot));
        depot.setDepotLevel(SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("门店", "depotLevel"));
        Depot flush = SpringManager.getBean(DepotRepository.class).saveAndFlush(depot);
        //生成仓库库区
        Location location = new Location();
        String name = company.getName() + "带安库";
        location.setCompany(company);
//        location.setId(id);
//        location.setDept(dept); 不写部门
        location.setName(name);
        location.setDepot(flush);
//        location.setDepotLevel(SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("门店","depotLevel"));
        StockUsage stockUsage = new StockUsage();
        stockUsage.setId("A");
        location.setUsage(stockUsage);
        location.setSalesAutoDelivery(true);
        location.setValid(true);
        location.setId(location.obtainLocationId(location));
        SpringManager.getBean(LocationRepository.class).saveAndFlush(location);
    }

    /**
     * 写入角色对照表
     *
     * @param party
     */
    private void writeContrastPartyCode(Party party) {
        ContrastPartyCode contrastPartyCode = new ContrastPartyCode();
        String company = partyRoleRepository.findByPartyIdAndRoleId(party.getId(), "Company").getId();
        contrastPartyCode.setParty(party);
        contrastPartyCode.setGsid(company);
        contrastPartyCode.setGysid("G" + company);
        contrastPartyCode.setKhid("K" + company);
        contrastPartyCodeRepository.saveAndFlush(contrastPartyCode);
    }

    /**
     * 写入本地权限
     *
     * @param company
     */
    public void synLocalPermit(PartyRole company, JSONObject body) {
        JSONObject synBDQX = new JSONObject();
        synBDQX.put("BDQXID", company.getId() + "00000");
        synBDQX.put("BDQXMC", company.getName());
        synBDQX.put("QXFWID", "01");
        synBDQX.put("DBCN", "ERP");
        synBDQX.put("TS01", DateUtils.format(new Date(), "yyyyMMdd.HHmmss.SSS"));
        synBDQX.put("LRR", "admin");
        synBDQX.put("LRRQ_SJ", DateUtil.format(company.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
//        String topic = "event:cm.branchEntry.synBDQX";
//        Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synBDQX).stream().findFirst().get();
//        if (!flg){
//            throw new RuntimeException("同步本地权限到旧框架时报错!");
//        }
        body.put("BDQX", synBDQX);

        //权限明细
        JSONArray localPermitItems = new JSONArray();
        //公司权限
        JSONObject synGSQXMX = new JSONObject();
        synGSQXMX.put("BDQXID", company.getId() + "00000");
        synGSQXMX.put("QXWDID", "GSID");
        synGSQXMX.put("CZQX", company.getId());
        synGSQXMX.put("CXQX", company.getId());
        localPermitItems.add(synGSQXMX);
        //采购组织权限
        JSONObject synCGZZMX = new JSONObject();
        synCGZZMX.put("BDQXID", company.getId() + "00000");
        synCGZZMX.put("QXWDID", "CGZZID");
        synCGZZMX.put("CZQX", company.getId());
        synCGZZMX.put("CXQX", company.getId());
        localPermitItems.add(synCGZZMX);
        //销售组织权限
        JSONObject synXXZZMX = new JSONObject();
        synXXZZMX.put("BDQXID", company.getId() + "00000");
        synXXZZMX.put("QXWDID", "XSZZID");
        synXXZZMX.put("CZQX", company.getId());
        synXXZZMX.put("CXQX", company.getId());
        localPermitItems.add(synXXZZMX);
//        String BDQXMXtopic = "event:cm.branchEntry.synBDQXMX";
//        Boolean BDQXMXflg = (Boolean) EventUtil.sendSynEvent(this, BDQXMXtopic, synBDQXMX).stream().findFirst().get();
//        if (!BDQXMXflg){
//            throw new RuntimeException("同步本地权限明细到旧框架时报错!");
//        }
        body.put("BDQXMX", localPermitItems);
    }

    /**
     * 推送同步消息至老系统
     *
     * @param request
     */
    @Consumer(topic = "cm.companyEntry.synUnifiedExport")
    private void synUnifiedExport(SimpleRequest request) {
        String topic = "event:cm.companyEntry.synUnifiedExport";
        EventUtil.sendSynEvent(this, topic, request.getJO()).stream().findFirst().get();
    }
}
